var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
var multiparty = require('multiparty')
var xlsx = require('node-xlsx')

var { roleModel, teacherModel, documentModel, disciplineModel, postModel, classModel, gradeModel, PreparingModel, userModel,studentModel,banjiModel,termModel,typeModel,HomeworkModel, topicModel,zhengModel } = require("../model/model")
const Core = require('@alicloud/pop-core'); // 引入阿里云 SDK
const app = express();
app.use(express.json()); // 解析请求中的 JSON 数据

// getRole
router.get("/getRole", async (req, res) => {
    let roleList = await roleModel.find()
    res.send({
        roleList
    })
})


router.post('/upload', async (req, res) => {
    let length = await teacherModel.countDocuments()
    let num = 0
    let from = new multiparty.Form()
    from.uploadDir = 'upload'
    from.parse(req, (err, a, xls) => {
        let data = xlsx.parse(xls.file[0].path)
        data = data[0].data
        data.shift()
        let list = []
        data.forEach(i => {
            num += 1
            list.push({
                id: length + num,
                name: i[0],
                sex: i[1],
                number: i[2],
                phone: i[3],
                emait: i[4],
                ori: i[5],
                discipline: i[6],
                post: i[7],
                class: i[8],
                grade: i[9],
                document: i[10]
            })
        })
        if(xlsx.parse(xls.file[0].path)[0].name=='学生'){
                studentModel.create(list)
        }else if(xlsx.parse(xls.file[0].path)[0].name=='老师'){
                teacherModel.create(list)
        }else{
            banjiModel.create(list)
        }
        
    })
})

router.get('/list', async (req, res) => {
    let a = req.query
    let teacher = await teacherModel.find(a).populate(['document', 'discipline', 'post', 'class', 'grade'])
    let document = await documentModel.find()
    let discipline = await disciplineModel.find()
    let post = await postModel.find()
    let clas = await classModel.find()
    let grade = await gradeModel.find()
    let length = await teacherModel.countDocuments()
    let student = await studentModel.find(a).populate(['document','class', 'grade'])
    let slength=await studentModel.countDocuments()
    res.send({
        teacher,
        document,
        discipline,
        post,
        clas,
        grade,
        length,
        slength,
        student
    })

});//获取数据
router.get('/list_student', async (req, res) => {
    let a = req.query
    let document = await documentModel.find()
    let clas = await classModel.find()
    let grade = await gradeModel.find()
    let student = await studentModel.find(a).populate(['document','class', 'grade'])
    let slength=await studentModel.countDocuments()
    res.send({
        document,
        clas,
        grade,
        slength,
        student
    })

});//获取数据
router.get('/list_banji', async (req, res) => {
    let a = req.query
    let clas = await classModel.find()
    let grade = await gradeModel.find()
    let teacher=await teacherModel.find()
    let student=await studentModel.find()
    let term=await termModel.find()
    let type=await typeModel.find()
    let banji = await banjiModel.find(a).populate(['class', 'grade','term','ca','type'])
    let blength=await banjiModel.countDocuments()
    res.send({
        blength,
        clas,
        grade,
        teacher,
        student,
        term,
        type,
        banji
    })

});//获取数据
router.post('/add', async (req, res) => {
    await teacherModel.create(req.body)
    res.send({
        code: 200
    })
})
router.post('/add_student', async (req, res) => {
  console.log(req.body);
  
    await studentModel.create(req.body)
    res.send({
        code: 200
    })
})
router.post('/add_banji', async (req, res) => {
  console.log(req.body);
  
    await banjiModel.create(req.body)
    res.send({
        code: 200
    })
})


//备课列表获取
router.get('/getprepar',async function(req, res) {
  let {name,teacher,bktype,discipline,grade,audit,start,end,page,pageSize}=req.query
  let a=[{}]
  if (name) {
    let regname=new RegExp(name)
    a.push({name:regname})
  }
  if (teacher) {
    let regname=new RegExp(teacher)
    a.push({teacher:regname})
  }
  if (bktype) {
    a.push({bktype:bktype})
  }
  if (discipline) {
    a.push({discipline:discipline})
  }
  if (grade) {
    a.push({grade:grade})
  }
  if(audit){
    a.push({audit:audit})
  }
  if(start){
    a.push({data:{$gte:start}})
  }
  if(end){
    a.push({data:{$lte:end}})
  }
  let prepar=await PreparingModel.find({$and:a})
  let total=prepar.length
  res.send({
    prepar,
    total
  })
})
//备课实例列表获取
router.get('/getprepar1',async function(req, res) {
  let {name,teacher,bktype,discipline,grade,page,pageSize}=req.query
  let a=[{instance:true}]
  if (name) {
    let regname=new RegExp(name)
    a.push({name:regname})
  }
  if (teacher) {
    let regname=new RegExp(teacher)
    a.push({teacher:regname})
  }
  if (bktype) {
    a.push({bktype:bktype})
  }
  if (discipline) {
    a.push({discipline:discipline})
  }
  if (grade) {
    a.push({grade:grade})
  }
  let prepar=await PreparingModel.find({$and:a})
  let total=prepar.length
  res.send({
    prepar,
    total
  })
})
//备课实例添加
router.post('/addprepar',async function(req, res) {
  await PreparingModel.create(req.body)
  res.send({
    code:200
  })
})
//备课质量
router.post('/editprepar', async (req,res)=>{
  let {id,quality}=req.body
  await PreparingModel.updateOne({_id:id},{quality:quality})
  res.send({
    code:200
  })
})

//备课实例
router.post('/editInstance', async (req,res)=>{
  let {id,instance}=req.body
  console.log(req.body);
  await PreparingModel.updateOne({_id:id},{instance:instance})
  res.send({
    code:200
  })
})
//备课审核
router.post('/editaudit', async (req,res)=>{
  let {id,audit}=req.body
  console.log(req.body);
  await PreparingModel.updateOne({_id:id},{audit:audit})
  res.send({
    code:200
  })
})
//备课统计
router.get('/getNumber', async (req,res)=>{
  let total=(await PreparingModel.find()).length
  let teaching=(await PreparingModel.find({bktype:'教案'})).length
  let tutorial=(await PreparingModel.find({bktype:'导学案'})).length
  let cour=(await PreparingModel.find({bktype:'课件'})).length
  let quality1= await PreparingModel.find({quality:'优秀'})
  let quality2= await PreparingModel.find({quality:'良好'})
  let quality3= await PreparingModel.find({quality:'合格'})
  let quality4= await PreparingModel.find({quality:'不合格'})
  let data=[
    { value: quality1.length, name: '优秀' },
    { value: quality2.length, name: '良好' },
    { value: quality3.length, name: '合格' },
    { value: quality4.length, name: '不合格' },
  ]
  res.send({
    total,//备课总数量
    teaching,
    tutorial,
    cour,
    data
  })
})



// 访问令牌有效期
const ACCESS_TOKEN_EXPIRATION='1h'
// 刷新令牌有效期
const REFRESH_TOKEN_EXPIRATION='1d'
const SECRET_KEY="MTHGH"
const refreshTokenMap=new Map()

// 生成函数令牌
function generateToken(name,expiration){
  return jwt.sign({name},SECRET_KEY,{expiresIn:expiration})
}

// 封装生成长token和短token
function getToken(name){
  let accessToken = generateToken(name,ACCESS_TOKEN_EXPIRATION)
  let refreshToken = generateToken(name,REFRESH_TOKEN_EXPIRATION)
  const refreshTokens = refreshTokenMap.get(name)||[]
  refreshTokens.push(refreshToken)
  refreshTokenMap.set(name,refreshTokens)
  return {
    accessToken,
    refreshToken
  }
}

// 账号密码登录
router.post('/userLogin', async (req, res) => {
  const {username,password} = req.body
  let user = await userModel.findOne({userName:username})
  if(!user){
    return res.status(200).send({message:"账号错误",code:1})
  }
  if(user.passWord!==password){
    return res.status(200).send({message:"密码错误",code:2})
  }
  let {accessToken,refreshToken}=getToken(user.userName)
  res.status(200).send({
    data:user,
    accessToken,
    refreshToken,
    message:'登陆成功',
    code:200
  })
})
//zhu
// router.get('/search', async (req, res) => {
//   console.log(req.query,'111111111111');
  
// })
//列表渲染
router.get('/as', async (req, res) => {
  let xk=req.query.xk
  let xd = req.query.xd
  let nj = req.query.nj
  let bj = req.query.bj
  console.log(xk,xd,nj,bj);
  let serch = {}
  if (xk !='') { 
    serch.discipline=xk
  }
  if (xd!='') {
    serch.semester = xd
  }
  if (nj!='') {
    serch.grade = nj
  }
  if (bj!='') {
    serch.age = bj
  }
  console.log(serch);

    let data = await HomeworkModel.find(serch)
  res.send({
    data
  })
})
  
router.get('/homework', async (req, res) => {
    let data =await HomeworkModel.find()
  res.send({
      data:data
    })
  })
router.get('/title', async (req, res) => {
  let data = await HomeworkModel.find()
  let title = []
  data.forEach(i => {
    title.push(i.title)
  })
  res.send({
    title: title,
    data: data
  })


})
router.get('/topic', async (req, res) => {
  let data = await topicModel.find()
  let dataa = await zhengModel.find()
  res.send({
    data: data,
    dataa:dataa
  })
})




// 刷新短token
router.get('/refresh',async(req,res)=>{
  const refreshToken = req.headers.refreshtoken
  // console.log(111);
  
  if(!refreshToken){
    res.status(403).send("没有短token")
  }
  try{
    const {name} = jwt.verify(refreshToken,SECRET_KEY)
    const accessToken = generateToken(name,ACCESS_TOKEN_EXPIRATION)
    res.status(200).send({accessToken})
  }catch(error){
    console.log('长token已经过期');
    res.status(403).send('长token已经过期')
    
  }
})

// 阿里云短信验证
const client = new Core({ // 创建 Client 对象
  accessKeyId: 'LTAI5tCtk5zd4U37TzPkapr8', // 替换成自己的 AccessKey ID
  accessKeySecret: 'ptF2yI9FI2FcbKj4cFjF6kV90IMCvT', // 替换成自己的 AccessKey Secret
  endpoint: 'https://dysmsapi.aliyuncs.com', // API 访问入口，根据实际情况修改
  apiVersion: '2017-05-25' // API 版本号，根据实际情况修改
});

let yanzhengma = ''
// 生成随机验证码
function generateCode() {
  const code = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
  // yanzhengma = code.toString()
  return code.toString();
}

// 发送短信验证码
router.post('/sendYzm', (req, res) => {
  const phoneNumber = req.body.phone; // 获取手机号码
  console.log(phoneNumber);
  
  const code = generateCode(); // 生成验证码
  // console.log(code);
  
  yanzhengma = code // 找回密码的校验，yanzhengma存储的是生成的验证码
  const params = {
    "RegionId": "cn-hangzhou", // 短信服务所在区域，可以参考阿里云文档
    "PhoneNumbers": phoneNumber, // 目标手机号码
    "SignName": "小马哥", // 短信签名名称，需先在阿里云控制台中申请审核通过
    "TemplateCode": "SMS_479145410", // 短信模板 CODE，需先在阿里云控制台中申请审核通过
    "TemplateParam": JSON.stringify({ // 短信模板参数，为 JSON 字符串格式
      "code": code // 模板中的变量名和对应的值
    })
  };
 
  const requestOption = { // 设置请求超时时间等选项
    method: 'POST',
    timeout: 5000
  };
  // 调用 SendSms 方法发送短信
  client.request('SendSms', params, requestOption).then((result) => {
    console.log(result); // 打印发送结果
 
    res.status(200).json({ // 返回状态码和生成的验证码
      message: '验证码已发送，请注意查收！',
      code: code
    });
  }, (ex) => {
    console.log(ex); // 打印异常信息
 
    res.status(500).json({ // 返回错误状态码和错误信息
      message: '短信发送失败，请稍后重试！'
    });
  });
});
// 重置密码
router.post('/resetPassword', async(req, res) => {
  const phoneNumber = req.body.phone; // 获取手机号码
  const newPassword = req.body.newPassword // 获取用户输入的新密码
  await userModel.updateOne({phone:phoneNumber},{passWord:newPassword})
  res.send({
    code:200,
    message:"重置成功"
  })
});

// 判断用户是否存在
router.get("/findUser",async(req,res)=>{
  const user = await userModel.find({userName:req.query.username})
  
  if(user.length>0){
    res.send({
      message:'成功',
      code:200,
      phone:user[0].phone
    })
  }else{
    res.send({
      message:"用户不存在！",
      code:401
    })
  }})


router.post('/update', async (req, res) => {
    let _id=req.body._id
    await teacherModel.updateOne({_id:_id},req.body)

    res.send({
        code: 200
    })
})
router.post('/update_student', async (req, res) => {
    let _id=req.body._id
    await studentModel.updateOne({_id:_id},req.body)

    res.send({
        code: 200
    })
})
router.post('/update_banji', async (req, res) => {
    let _id=req.body._id
    await banjiModel.updateOne({_id:_id},req.body)

    res.send({
        code: 200
    })
})
router.get('/dele', async (req, res) => {
    let _id=req.query._id
    await teacherModel.deleteOne({_id:_id})

    res.send({
        code: 200
    })
})
router.get('/dele_student', async (req, res) => {
    let _id=req.query._id
    console.log(_id);
    await studentModel.deleteOne({_id:_id})
    res.send({
        code: 200
    })
})
router.get('/dele_banji', async (req, res) => {
    let _id=req.query._id
    console.log(_id);
    await banjiModel.deleteOne({_id:_id})
    res.send({
        code: 200
    })
})

module.exports = router;
